package com.example.waimaiandroid.billing;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.example.waimai.HttpUtil.MyPost;
import com.example.waimai.MainActivity;
import com.example.waimai.context.UserInfoContext;
import com.example.waimai.pojo.Food;
import com.example.waimai.pojo.Orders;
import com.example.waimai.pojo.UserAddress;
import com.example.waimai.ui.home.HomeFragment;
import com.example.waimai.util.MyThreadPool;
import com.example.waimai.util.TimeStampFormatUtil;
import com.example.waimaiandroid.R;
import com.example.waimaiandroid.addAddress.addAddress;
import com.example.waimaiandroid.address.AddressActivity;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BillingActivity extends AppCompatActivity {
    Orders order;
    String storeName;
    TextView mAddress;
    TextView mInfo;
    TextView mStoreName;
    ImageView mUpdateAddr;
    MyListViewForScrollView mOrderFoods;
    OrderPostAdapter mOrderPostAdapter;
    Button mPostOrder;
    // 下方的总金额
    TextView mBottomOrderPrice;
    // 备注
    ImageView mAddRemark;
    // 备注内容
    TextView mRemark;
    // 配送费
    TextView mDeliveryFee;
    // 总费用
    TextView mOrderPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX); // 表示使用沙箱调试环境
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplication());
        setContentView(R.layout.activity_billing);

        initData();
        initView();

    }

    private void initData(){
        Bundle extras = getIntent().getExtras();
        order = (Orders) extras.getSerializable("Order");
        storeName = extras.getString("StoreName");
        // 处理一下Order 的数据   处理什么？
        /*配送费： 根据距离计算吧 （未完成）
        *  备注： 默认是无 （事件监听中再添加）
        *  startTime : 开始事件  点击提交订单时生成
        *   orderStatus ； 订单状态 默认是未接单0 由商家那边去处理
        * 骑手的id ： 由 骑手端那边设置
        *  foodList : 记录菜品Id 和数量 ： 格式 菜品ID-数量#菜品Id-数量
       * */
        StringBuilder str = new StringBuilder();
        List<Food> foods = order.get_foodList();
        for(int i =0; i< foods.size();i++){
            if( i != 0){
                str.append(',');
            }
            str.append(foods.get(i).getId());
            str.append('-');
            str.append(foods.get(i).getAddNums());
        }
        order.setFoodIdList(str.toString());
        order.setUserStatus(0);
        order.setStoreStatus(0);
        order.setRiderStatus(0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0){
            if(resultCode == 0){
                // 从地址选择页面返回过来的 ，且地址正确
                // 获取数据
                Bundle extras = data.getExtras();
                UserAddress userAddress = (UserAddress) extras.getSerializable("userAddress");
                // 判断地址是否有超出配送范围
                LatLng userLat = new LatLng(Double.parseDouble(userAddress.getLatitude()),Double.parseDouble(userAddress.getLongitude()));
                LatLng stroeLat = new LatLng(Double.parseDouble(order.getStoreAddress().getLatitude()),Double.parseDouble(order.getStoreAddress().getLongitude()));
                double distance= DistanceUtil.getDistance(userLat, stroeLat);
                if(distance <=5000){
                    // 修改一下
                    UserInfoContext.userReceiveAddr = userAddress;
                    // 更新一下数据
                    mAddress.setText(UserInfoContext.userReceiveAddr.getAddress()+"  "+UserInfoContext.userReceiveAddr.getBottom());
                    mInfo.setText(UserInfoContext.userReceiveAddr.getReceiveName()+"  "+UserInfoContext.userReceiveAddr.getTelephone());
                }else{
                    // 提示超出配送范围
                    Toast.makeText(this,"超出配送范围，请重新选择收货地址！",Toast.LENGTH_SHORT).show();
                    mAddress.setText("超出配送范围，请重新选择收货地址");
                    mInfo.setText("");
                }

            }else if(resultCode == 1){
                // 从添加备注页面返回过来的
                String remark = data.getStringExtra("remark");
                order.setRemark(remark);
                mRemark.setText(remark);
                Toast.makeText(this,"添加备注成功！",Toast.LENGTH_SHORT).show();
            }else if(resultCode == 2){
                // 备注页面返回
            }
        }
    }

    private void initView(){
        mAddress = findViewById(R.id.myAddr);
        mInfo = findViewById(R.id.myInfo);
        mUpdateAddr = findViewById(R.id.updateAddr);
        mStoreName = findViewById(R.id.storeName);
        mOrderFoods = findViewById(R.id.orderFoods);
        mPostOrder = findViewById(R.id.postOrder);
        mBottomOrderPrice = findViewById(R.id.BottomOrderPrice);
        mAddRemark = findViewById( R.id.addRemark);
        mRemark = findViewById(R.id.remark);
        mDeliveryFee = findViewById(R.id.deliveryFee);
        mOrderPrice = findViewById(R.id.orderPrice);

        mOrderPostAdapter = new OrderPostAdapter(order.get_foodList(),this);
        mOrderFoods.setAdapter(mOrderPostAdapter);

        ( (ScrollView)findViewById(R.id.myScrollView)).smoothScrollTo(0,0);

        mStoreName.setText(storeName);
        // 设置一下一些基础信息
        // 地址信息展示
        mAddress.setText(UserInfoContext.userReceiveAddr.getAddress()+"  "+UserInfoContext.userReceiveAddr.getBottom());
        mInfo.setText(UserInfoContext.userReceiveAddr.getReceiveName()+"  "+UserInfoContext.userReceiveAddr.getTelephone());
        mDeliveryFee.setText("222"); // 配送费
        mOrderPrice.setText(String.valueOf(order.getTotalPrice()));
        mBottomOrderPrice.setText(String.valueOf(order.getTotalPrice()));

        // 选择地址
        mUpdateAddr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到地址选择页面，需要带返回值
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(BillingActivity.this, AddressActivity.class));
                intent.putExtra("fromActivity","BillingActivity");
                BillingActivity.this.startActivityForResult(intent,0);
            }
        });

        // 设置备注信息
        mAddRemark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到备注添加页面，需要带返回值
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(BillingActivity.this,remarkActivity.class));
                String remark =mRemark.getText().toString();
                if(null == remark || "".equals(remark)){
                    remark = "无";
                }
                intent.putExtra("remark",remark);
                BillingActivity.this.startActivityForResult(intent,0);
            }
        });


        // 提交订单其实就是调用支付请求
        /*
        * 先获取到 ordrInfo   通过服务端来获取
        *  先传入 AlipayBean 参数给服务端 传入一下基本的信息
        * PayTask alipay = new PayTask(PayDemoActivity.this);
				Map<String, String> result = alipay.payV2(orderInfo, true); // 发送支付请求？
				Log.i("msp", result.toString());

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
        * */
        mPostOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 先判断信息是否都完整了
                String s = mInfo.getText().toString();
                if(s==null || s.equals("")){
                    Toast.makeText(BillingActivity.this,"请选择收货地址！",Toast.LENGTH_SHORT).show();
                    return ;
                }
                // 其实都可以交给 服务端来处理的。
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        Map<String,String> param = new HashMap<>();
                        param.put("totalPrice", String.valueOf(order.getTotalPrice()));
                        String OrderInfo = (String) MyPost.doPost("getOrderInfo",param);
                        Log.e("OrderInfo",OrderInfo);
                        PayTask alipay = new PayTask(BillingActivity.this);
                        Map<String,String> result = alipay.payV2(OrderInfo,true);
                        Log.e("AliPayResult",result.toString());
                        // 生成订单信息，上传到服务器。  同时跳转到订单界面
                        order.setDeliveryFee(22f);
                        order.setUserAddressId(UserInfoContext.userReceiveAddr.getId());
                        order.setStartTime(TimeStampFormatUtil.getCurrentTime());
                        order.setUserId(UserInfoContext.mUser.getId());
                        order.setRemark(mRemark.getText().toString());
                        order.setUserStatus(1);
                        order.setRiderStatus(0);
                        order.setStoreStatus(0);
                        // 发起一个上传订单的请求
                        String url = "postOrder";
                        order = (Orders) MyPost.doPost(url,order);
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName(BillingActivity.this, MainActivity.class));
                        intent.putExtra("toOrderList",true);
                        HomeFragment.view = null;
                        BillingActivity.this.startActivity(intent);
                        BillingActivity.this.finish();
                    }
                });
            }
        });


    }
}